import { render } from 'react-dom'
import { createRoot } from 'react-dom/client'
import Message from './MessageBox'

type TMessage = {
  [key in TMessageTypeType]?: Function
}
type TMessageTypeType = 'info' | 'success' | 'error' | 'warnning'
const typeArr: TMessageTypeType[] = ['info', 'success', 'error', 'warnning']
let nodeArr: HTMLDivElement[] = []
const message: TMessage & { closeAll?: Function } = {}
typeArr.forEach(type => {
  message[type] = (content: string, duration = 3000) => {
    let node = document.createElement('div')
    document.body.appendChild(node)
    nodeArr.push(node)
    node.style.position = 'absolute'
    node.style.top = nodeArr.length * 55 + 'px'
    node.style.left = '0'
    node.style.right = '0'
    node.style.margin = 'auto'
    node.style.width = '75%'
    node.style.transition = 'all 0.3s'
    createRoot(node).render(Message({ content, type }))
    setTimeout(() => {
      nodeArr.shift()
      nodeArr.forEach(item => (item.style.top = parseInt(item.style.top) - 50 + 'px'))
      document.body.removeChild(node)
    }, duration)
    return () => {
      document.body.removeChild(node)
    }
  }
})
message.closeAll = () => {}
export default message
